//-------------------------------------------------------------------------------------------------
// author zhangwei on 2015.08.10
// modified by zhangwei on 2015.08.10
// - Released ver v1. This version is the clone from: https://github.com/TahaSh/Tasks-App-With-VueJS
//   And there's a good article about it: http://taha-sh.com/blog/many-js-frameworks-but-vuejs-is-different 
// modified by zhangwei on 2015.08.10
// - Released ver 2. This is a readonly list.
//
// modified by zhangwei on 2015.08.28
// - Add grid component.
//
// Reference
// - http://taha-sh.com/blog/many-js-frameworks-but-vuejs-is-different 
//-------------------------------------------------------------------------------------------------


// TODO on 2015.08.23
// - Uses vue-resource to fetch data from the backend or jQuery ajax to communicate with backend service.
// - Suggest use the standard code pattern in vue grid/table examples. 
//   Better encapsulate the table as a component.

Array.removeRange = function(array, from, to) {
    var rest = array.slice((to || from) + 1 || array.length);
    array.length = from < 0 ? array.length + from : from;
    return array.push.apply(array, rest);
};

function removeAt(array,idx)  
{  
        if(! Array.prototype.isPrototypeOf(array)){  
            return null;//根据Null可以判断本次调用失败  
        }  
        var idx = parseInt(idx),  
            iLen = idx.length;  
        if(idx < 0 || idx >= iLen){  
            return null;//根据Null可以判断本次调用失败  
        }  
        var aRet = [];//与NULL不同  
        return aRet=array.slice(0,idx).concat(array.slice(idx+1));  
}  

var AppService = {

	name: "Application Service Used by the Vue Layer(View Layer)",

	init: function(){

	},

	_find: function(pagenum, pagesteps){
		var data = [];
		for (var i=0; i<pagesteps; i++)
		{
			data.push({
	            rowid: i, 
				selected: (i % 2 == 0), 
				timestamp: '2015.07.08Z23:12:56:324:313', 
				node: '3213121', 
				frame: '56 7F 2A 3D', 
				title: 'Go to grocery store' + i, 
				completed: false
	 		});
		}
		return data;
	},

	load: function(ctx, succ_callback, fail_callback) {
		$.ajax({
			context: ctx,
			url: "/rest/istream",
                success: function (result) {
                	succ_callback(result)
                }
        })
    },

    remove: function(id)
    {

    }
};


var svc = Object.create(AppService);

var vm = new Vue({
    el: '#app',
	
	data: {
		begintime: '',
		endtime: '',
		remotedevice: '',
		searchQuery: '',
		
        items: [
            { rowid: 3, selected: true, timestamp: '2015.07.08Z23:12:56:324:313', node: '3213121', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
            { rowid: 4, selected: false, timestamp: '2015.07.08Z23:12:56:325:313', node: '3213121', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
            { rowid: 5, selected: true, timestamp: '2015.07.08Z23:12:56:327:313', node: '3213123', frame: '56 7F 2A 3D', title: 'Go to grocery store', completed: false },
        ],
		
		tempselected: true,
    },
	
	methods: {
		search: function(e){
			console.log("search button");
			console.log(e.target.tagName); // "BUTTON"
			console.log(e.targetVM === this); // true
			var inputs = new Array();
			inputs[0] = "{begintime:'";
			inputs[1] = this.begintime;
			inputs[2] = "', endtime:'";
			inputs[3] = this.endtime;
			inputs[4] = "', remotedevice:'";
			inputs[5] = this.remotedevice;
			inputs[6] = "', searchQuery:'";
			inputs[7] = this.searchQuery;
			inputs[8] = "'}";
			inputQuery = inputs.join('');
			console.log("your input query condition is " + inputQuery);
			_find(this, inputQuery, 1, 6);
		},
		
		_find: function(vm, inputQuery, pagenumber, pagesteps){
		    setTimeout(function (){
				var data =  svc._find(pagenumber, pagesteps);
				var tmplen = vm.items.length;
				for (var i=0; i<pagesteps; i++)
				{
					data[i].rowid = tmplen + i;
					//vm.items.push(data[i]);
				}
				vm.$set('items', data);
		    }, 100)
		},

        // TODO: test with backend
		onFetchItems: function() {
			$.ajax({
				context: this,
				url: "/rest/istream",
                success: function (result) {
                	this.$set("items", result) 
                }
            })
        },

		onFetchItems2: function() {
			svc.load(this, function(result){
				this.$set("items", result) 
			}, null);
        },

		/*
        clearData : function (){
			console.log("clear button");
            var myTable = VueUI.getComponent('myTable')
            VueUI.resetArray(tableConf.data, [])
            //tableConf.data = []
            //tableConf.data = []
            //myTable.data = []
            myTable.totalPage = 0
            myTable.totalCount = 0
        }
		*/
		
		//sortBy: function (key) {
		//	this.sortKey = key
		//	this.reversed[key] = !this.reversed[key]
		//}

		// Only for demonstration. Not necessary for this module.
		onAddNew: function(e) {
			e.preventDefault()
			$.ajax({
				context: this,
                type: "POST",
                data: {
                	//item：this.item,
					//author: this.author,
                    text: this.text
                },
                url: "/rest/inputstream",
				success: function(result) {
					this.items.push(result);
                    this.author = ''
                    this.text = ''
                    }
                })                        
            },

        // TODO: test with backend
  		removeItem: function(item, e){
  			console.log('removeItem' + item);
			$.ajax({
				context: item,
                type: "DELETE",
                url: "/rest/inputstream/" + item.id,
            })
            this.items.$remove(item);
  		},

		// delete each item according to the item.selected property
		removeSelected: function(e){
			console.log("removeSelected: " + e);
			var items = this.items;
			console.log(items);
			for (var i in items){
				if (items[i].selected == true)
				{
					console.log(items[i] + ' is to be deleted!!!');
					this.removeItem(items[i],null);
				}
			}
		}
	},
	
	ready: function(){
		console.log("ready function is called");
		svc.init();
		
		// @tutorial call find/fetch here to load initial data.
		this._find(this, '', 1, 6);
	}
});

// equvalent to $(document).ready(function(){...}
$(function () {
	// Specify the tab to be displayed at first.
    //$('#myTab a:last').tab('show');
	$('#myTab a[href="#home"]').tab('show');
          
    $('#myTab a').click(function (e) {
		e.preventDefault(); // Prevent the default link behavior ×èÖ¹aÁ´½ÓµÄÌø×ªÐÐÎª
        $(this).tab('show'); // Display the content of the specified tab
		});
});
  



